<?php
if (!defined('ABSPATH')) { exit; }

function scf_username_from_email($email) {
    $email = strtolower(trim($email));
    if (!is_email($email)) return 'user';
    $parts = explode('@', $email);
    $local = preg_replace('/[^a-z0-9]+/i', '_', $parts[0]);
    $domain = isset($parts[1]) ? preg_replace('/[^a-z0-9]+/i', '_', $parts[1]) : '';
    $base = trim(preg_replace('/_+/', '_', $local . '_' . $domain), '_');
    if ($base === '') $base = 'user';
    return $base;
}

function scf_user_register_shortcode($atts = []) {
    if (is_user_logged_in()) {
        $u = wp_get_current_user();
        ob_start();
        ?>
        <div class="scf-card scf-user">
            <div class="scf-card__header"><strong>用户中心</strong></div>
            <div class="scf-card__body">
                <p>您已登录：<?php echo esc_html($u->display_name ?: $u->user_login); ?></p>
                <p><a href="<?php echo esc_url(wp_logout_url(get_permalink())); ?>" class="button">退出登录</a></p>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    $errors = new WP_Error();
    $messages = [];
    $email = '';

    $is_post = ($_SERVER['REQUEST_METHOD'] === 'POST'
        && isset($_POST['scf_user_register_nonce'])
        && wp_verify_nonce($_POST['scf_user_register_nonce'], 'scf_user_register'));

    if ($is_post) {
        $email = isset($_POST['scf_email']) ? sanitize_email($_POST['scf_email']) : '';
        $pass1 = isset($_POST['scf_password']) ? $_POST['scf_password'] : '';
        $pass2 = isset($_POST['scf_password_confirm']) ? $_POST['scf_password_confirm'] : '';

        if (!is_email($email)) {
            $errors->add('invalid_email', '邮箱格式不正确');
        } elseif (email_exists($email)) {
            $errors->add('email_exists', '该邮箱已注册');
        }
        if (strlen($pass1) < 6) {
            $errors->add('weak_password', '密码至少 6 位');
        }
        if ($pass1 !== $pass2) {
            $errors->add('pass_mismatch', '两次密码不一致');
        }

        if (!$errors->has_errors()) {
            $username_base = scf_username_from_email($email);
            $username = $username_base;
            $i = 1;
            while (username_exists($username)) {
                $username = $username_base . $i;
                $i++;
            }
            $user_id = wp_insert_user([
                'user_login'   => $username,
                'user_email'   => $email,
                'user_pass'    => $pass1,
                'display_name' => $username,
                'role'         => get_option('default_role', 'subscriber'),
            ]);
            if (is_wp_error($user_id)) {
                $errors->add('register_failed', $user_id->get_error_message());
            } else {
                $creds = [
                    'user_login'    => $username,
                    'user_password' => $pass1,
                    'remember'      => true,
                ];
                $user = wp_signon($creds, false);
                if (is_wp_error($user)) {
                    $messages[] = '注册成功，请手动登录。';
                } else {
                    $messages[] = '注册并已登录成功。';
                }
            }
        }
    }

    ob_start();
    ?>
    <div class="scf-card scf-user scf-user-register">
        <div class="scf-card__header"><strong>邮箱注册</strong></div>
        <div class="scf-card__body">
            <?php if ($errors->has_errors()): ?>
                <div class="scf-errors">
                    <?php foreach ($errors->get_error_messages() as $msg): ?>
                        <p style="color:#b91c1c;"><?php echo esc_html($msg); ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($messages)): ?>
                <div class="scf-messages">
                    <?php foreach ($messages as $msg): ?>
                        <p style="color:#065f46;"><?php echo esc_html($msg); ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <form method="post">
                <?php wp_nonce_field('scf_user_register', 'scf_user_register_nonce'); ?>
                <p>
                    <label>邮箱：<br>
                        <input type="email" name="scf_email" value="<?php echo esc_attr($email); ?>" required placeholder="you@example.com">
                    </label>
                </p>
                <p>
                    <label>密码：<br>
                        <input type="password" name="scf_password" required minlength="6" placeholder="至少 6 位">
                    </label>
                </p>
                <p>
                    <label>确认密码：<br>
                        <input type="password" name="scf_password_confirm" required minlength="6">
                    </label>
                </p>
                <p>
                    <button type="submit" class="button">注册</button>
                </p>
            </form>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

function scf_user_login_shortcode($atts = []) {
    // 支持短码参数：redirect（登录成功后跳转目标）
    $atts = shortcode_atts([
        'redirect' => '',
    ], $atts, 'user_login');
    $redirect_url = $atts['redirect'] ? esc_url_raw($atts['redirect']) : '';

    if (is_user_logged_in()) {
        $u = wp_get_current_user();
        ob_start();
        ?>
        <div class="scf-card scf-user">
            <div class="scf-card__header"><strong>用户中心</strong></div>
            <div class="scf-card__body">
                <p>您已登录：<?php echo esc_html($u->display_name ?: $u->user_login); ?></p>
                <p>
                    <a href="<?php echo esc_url(wp_logout_url(get_permalink())); ?>" class="button">退出登录</a>
                </p>
            </div>
        </div>
        <?php
        return ob_get_clean();
    }

    $errors = new WP_Error();
    $messages = [];
    $email = '';
    $remember = false;
    $redirect_js = '';

    $is_post = ($_SERVER['REQUEST_METHOD'] === 'POST'
        && isset($_POST['scf_user_login_nonce'])
        && wp_verify_nonce($_POST['scf_user_login_nonce'], 'scf_user_login'));

    if ($is_post) {
        $email = isset($_POST['scf_email']) ? sanitize_email($_POST['scf_email']) : '';
        $password = isset($_POST['scf_password']) ? $_POST['scf_password'] : '';
        $remember = !empty($_POST['scf_remember']);

        if (!is_email($email)) {
            $errors->add('invalid_email', '邮箱格式不正确');
        } else {
            $user = get_user_by('email', $email);
            if (!$user) {
                $errors->add('no_user', '该邮箱未注册');
            } else {
                $creds = [
                    'user_login'    => $user->user_login,
                    'user_password' => $password,
                    'remember'      => $remember,
                ];
                $signed = wp_signon($creds, false);
                if (is_wp_error($signed)) {
                    $errors->add('login_failed', '登录失败：' . $signed->get_error_message());
                } else {
                    $messages[] = '登录成功！';
                    if (!empty($redirect_url)) {
                        $target = $redirect_url;
                        if (!headers_sent()) {
                            wp_safe_redirect($target);
                            exit;
                        } else {
                            $redirect_js = '<script>window.location.href=' . json_encode($target) . ';</script>';
                        }
                    }
                }
            }
        }
    }

    $lost_url = wp_lostpassword_url(!empty($redirect_url) ? $redirect_url : get_permalink());

    ob_start();
    ?>
    <div class="scf-card scf-user scf-user-login">
        <div class="scf-card__header"><strong>邮箱登录</strong></div>
        <div class="scf-card__body">
            <?php if ($errors->has_errors()): ?>
                <div class="scf-errors">
                    <?php foreach ($errors->get_error_messages() as $msg): ?>
                        <p style="color:#b91c1c;"><?php echo esc_html($msg); ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($messages)): ?>
                <div class="scf-messages">
                    <?php foreach ($messages as $msg): ?>
                        <p style="color:#065f46;"><?php echo esc_html($msg); ?></p>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($redirect_js)) echo $redirect_js; ?>

            <form method="post">
                <?php wp_nonce_field('scf_user_login', 'scf_user_login_nonce'); ?>
                <p>
                    <label>邮箱：<br>
                        <input type="email" name="scf_email" value="<?php echo esc_attr($email); ?>" required placeholder="you@example.com">
                    </label>
                </p>
                <p>
                    <label>密码：<br>
                        <input type="password" name="scf_password" required minlength="6">
                    </label>
                </p>
                <p>
                    <label>
                        <input type="checkbox" name="scf_remember" <?php echo $remember ? 'checked' : ''; ?>> 记住我
                    </label>
                </p>
                <p>
                    <button type="submit" class="button">登录</button>
                </p>
                <p>
                    <a href="<?php echo esc_url($lost_url); ?>">忘记密码？</a>
                </p>
            </form>
        </div>
    </div>
    <?php
    return ob_get_clean();
}